import React, { Component } from 'react';
import CustomForm from '../../../../components/CustomForm';
import { message, DatePicker } from 'antd';
import services from '../../../../services/api';
import moment from 'moment';

class SetValidTime extends Component {
  constructor(props) {
    super(props);
    this.form = null;
  }

  handleSubmit = () => {
    this.form.validateFields((err, values) => {
      if (!err) {
        const params = {
          name_list_data_ids: this.props.name_list_data_ids.join(),
          start_time: moment(values.start_time).format('YYYY-MM-DD HH:mm:ss'),
          end_time: moment(values.end_time).format('YYYY-MM-DD HH:mm:ss')
        };
        services.nameListDetail.setValidTime(params).then(data => {
          if (data.code === 0) {
            message.success(data.msg);
            if (this.props.closeModal) {
              this.props.closeModal();
            }
          } else {
            message.error(data.msg);
          }
        });
      }
    });
  };

  handleConfirmBlur = e => {
    const { value } = e.target;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };

  onStartTimeChange = (e, dateString) => {
    const start = e.startOf('day').format('YYYY-MM-DD HH:mm:ss');
    this.form.setFieldsValue({
      start_time: start
    });
  };
  onEndTimeChange = (e, dateString) => {
    const end = e.endOf('day').format('YYYY-MM-DD HH:mm:ss');
    this.form.setFieldsValue({
      end_time: end
    });
  };

  render() {
    const formItems = [
      {
        label: {
          label: '有效期始',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap'
        },
        name: 'start_time',
        options: {
          initialValue: this.props.start_time,
          rules: [{ required: true, message: '请选择' }]
        },
        component: (
          <DatePicker
            placeholder='请选择'
            style={{ width: '100%' }}
            format={'YYYY-MM-DD HH:mm:ss'}
            showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
          />
        )
      },
      {
        label: {
          label: '有效期止',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap'
        },
        name: 'end_time',
        options: {
          initialValue: this.props.end_time,
          rules: [{ required: true, message: '请选择' }]
        },
        component: (
          <DatePicker
            placeholder='请选择'
            style={{ width: '100%' }}
            format={'YYYY-MM-DD HH:mm:ss'}
            showTime={{
              defaultValue: moment('23:59:59', 'HH:mm:ss')
            }}
          />
        )
      }
    ];

    return (
      <CustomForm
        closeModal={() => this.props.closeModal(true)}
        createForm={ref => (this.form = ref)}
        formItems={formItems}
        onHandleSubmit={this.handleSubmit}
        colNum={1}
      />
    );
  }
}

export default SetValidTime;
